package com.ykzb.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DBUtil
{
	private static Log log = LogFactory.getLog(DBUtil.class.getName());

	public static String toFieldType(int columnType, int scale)
	{
		if (columnType == Types.BIGINT || (columnType == Types.LONGVARCHAR && scale == 0) || (columnType == Types.NUMERIC && scale == 0))
		{
			return "Long";
		}
		if (columnType == Types.BLOB)
		{
			return "Blob";
		}
		if (columnType == Types.CLOB)
		{
			return "Clob";
		}
		if (columnType == Types.TIMESTAMP || columnType == Types.DATE)
		{
			return "Date";
		}
		if (columnType == Types.DECIMAL)
		{
			return "Decimal";
		}
		if (columnType == Types.DOUBLE)
		{
			return "Double";
		}
		if (columnType == Types.FLOAT || columnType == 6 || columnType == Types.NUMERIC)
		{
			return "Float";
		}
		if (columnType == Types.INTEGER || (columnType == Types.NUMERIC && scale == 0))
		{
			return "Integer";
		}

		if (columnType == Types.VARCHAR)
		{
			return "String";
		}
		return "unknow";
	}

	public static boolean executeSQL(Statement statement, String sql)
	{
		try
		{
			statement.execute(sql);
		} catch (SQLException e)
		{
			return false;
		}
		return true;
	}

	public static boolean executeSQL(Statement statement, File sqlFile)
	{
		try
		{
			InputStream is = new FileInputStream(sqlFile);
			String line = null;
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			while ((line = reader.readLine()) != null)
			{
				line = line.trim();
				if (TopUtil.isValidValue(line))
				{
					log.info(line);
					executeSQL(statement, line);
				}
			}
			is.close();
			reader.close();
		} catch (FileNotFoundException e)
		{
			return false;
		} catch (IOException e)
		{
			return false;
		}
		return true;
	}
}
